package com.nlx.notes.module.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nlx.notes.module.bean.vo.AccountVO;
import com.nlx.notes.module.bean.vo.CategoryVO;
import com.nlx.notes.module.core.util.DataConvertorUtils;
import com.nlx.notes.module.entity.Accounts;
import com.nlx.notes.module.mapper.AccountsMapper;
import com.nlx.notes.module.service.IAccountsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nlx
 * @since 2024-12-15
 */
@Service
public class AccountsServiceImpl extends ServiceImpl<AccountsMapper, Accounts> implements IAccountsService {

    @Override
    public List<AccountVO> accountList(Long userId) {
        if(null == userId){
            return Collections.emptyList();
        }
        List<Accounts> accounts = this.findByUser(userId);
        if(CollUtil.isEmpty(accounts)){
            return Collections.emptyList();
        }
        return DataConvertorUtils.copyListProperties(accounts,AccountVO::new);
    }

    @Override
    public Map<Long ,String> findAccountMapByAccountIds(Set<Long> accountIds) {
        Map<Long ,String> accountMap = null;
        List<Accounts> accountsList = this.findAccountByAccountIds(accountIds);
        if(CollUtil.isNotEmpty(accountsList)){
            //将账号信息转成Map数据，供流水使用
            accountMap = accountsList.stream()
                    .collect(Collectors.toMap(Accounts::getAccountId, Accounts::getAccountName));
        }
        return accountMap;
    }

    @Override
    public List<Accounts> findAccountByAccountIds(Set<Long> accountIds) {
        return this.getBaseMapper().selectList(Wrappers.<Accounts>lambdaQuery().in(Accounts::getAccountId, accountIds));
    }

    @Override
    public String findAccountNameByAccountId(Long accountId) {
        if(null == accountId){
            return null;
        }
        Accounts accounts = this.getById(accountId);
        if(null == accounts){
            return null;
        }
        return accounts.getAccountName();
    }

    private List<Accounts> findByUser(Long userId) {
        if(null == userId){
            return Collections.emptyList();
        }
        return this.getBaseMapper().selectList(Wrappers.lambdaQuery(Accounts.class).eq(Accounts::getUserId,userId).or().isNull(Accounts::getUserId));
    }
}
